package com.example.picturebacked.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.picturebacked.annotation.AuthCheck;
import com.example.picturebacked.common.BaseResponse;
import com.example.picturebacked.common.DeleteRequest;
import com.example.picturebacked.common.ResultUtils;
import com.example.picturebacked.contant.UserContant;
import com.example.picturebacked.exception.BusinessException;
import com.example.picturebacked.exception.ErrorCode;
import com.example.picturebacked.exception.ThrowUtils;
import com.example.picturebacked.manager.auth.SpaceUserAuthManager;
import com.example.picturebacked.model.dto.space.*;
import com.example.picturebacked.model.entity.Space;
import com.example.picturebacked.model.entity.User;
import com.example.picturebacked.model.enums.SpaceLevelEnum;
import com.example.picturebacked.model.vo.SpaceVO;
import com.example.picturebacked.service.SpaceService;
import com.example.picturebacked.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/space")
@Api(tags = "空间接口")
public class SpaceController {

    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 增加空间
     */
    @PostMapping("/add")
    @ApiOperation("用户增加空间")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long newId = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(newId);
    }

    /**
     * 删除空间
     */
    @PostMapping("/delete")
    @ApiOperation("用户删除空间")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        Space deletespace = spaceService.getById(id);

        spaceService.checkSpaceAuth(deletespace, loginUser);
        // 删除空间接收返回值
        boolean b = spaceService.removeById(id);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新空间
     * 仅管理员可用
     */
    @PostMapping("/update")
    @ApiOperation("更新空间")
    @AuthCheck(mustRole = UserContant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest request) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Space space = new Space();
        BeanUtil.copyProperties(spaceUpdateRequest, space);
        spaceService.fillSpaceBySpaceLevel(space);

        // 数据校验
        spaceService.validSpace(space, false);
        Long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);

        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取空间（仅管理员可用，并且信息不脱敏）
     */
    @GetMapping("/get")
    @ApiOperation("管理员根据id获取空间")
    @AuthCheck(mustRole = UserContant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Space searchSpace = spaceService.getById(id);
        ThrowUtils.throwIf(searchSpace == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(searchSpace);
    }

    /**
     * 根据id获取空间（封装类） 用户使用
     */
    @GetMapping("/get/vo")
    @ApiOperation("用户根据id获取空间")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Space searchSpace = spaceService.getById(id);
        ThrowUtils.throwIf(searchSpace == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(searchSpace, request);
        User loginUser = userService.getLoginUser(request);
        // 获取权限，并将权限设置给spaceVO
        List<String> permissionList = spaceUserAuthManager.getPermissionList(searchSpace, loginUser);
        spaceVO.setPermissionList(permissionList);
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页获取空间列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @ApiOperation("管理员分页获取空间列表")
    @AuthCheck(mustRole = UserContant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                     HttpServletRequest request) {

        long current = spaceQueryRequest.getCurrent();
        long pageSize = spaceQueryRequest.getPageSize();
        // 根据当前页数以及页数据大小，通过使用getQueryWrapepr返回的查询条件进行分页查询
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize),
                spaceService.getQueryWrapepr(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }


    /**
     * 分页获取空间列表（用户使用）
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("用户分页获取空间列表")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                         HttpServletRequest request) {
        long current = spaceQueryRequest.getCurrent();
        long pageSize = spaceQueryRequest.getPageSize();
        // 限制爬虫，防止爬虫直接将所有空间都爬取
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize),
                spaceService.getQueryWrapepr(spaceQueryRequest));

        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }

    /**
     * 编辑空间（用户使用）
     */
    @PostMapping("/edit")
    @ApiOperation("用户编辑空间")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest,
                                           HttpServletRequest request) {
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Space space = new Space();
        BeanUtil.copyProperties(spaceEditRequest, space);
        // 更新编辑时间
        space.setEditTime(new Date());
        // 自动填充空间容量
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        Long id = spaceEditRequest.getId();
        Space editSpace = spaceService.getById(id);
        ThrowUtils.throwIf(editSpace == null, ErrorCode.NOT_FOUND_ERROR);
        spaceService.checkSpaceAuth(editSpace, loginUser);
        boolean b = spaceService.updateById(space);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 返回给前端一个数组，里面包含空间等级的详细信息
     * 每个空间等级包含等级名称，等级值，最大数量，最大容量
     *
     * @return
     */
    @GetMapping("/list/level")
    @ApiOperation("获取空间等级")
    public BaseResponse<List<SpaceLevel>> getSpaceLevel() {
        // 将枚举转为流然后通过每次新建一个对象转为List
        List<SpaceLevel> spaceLevelList = Arrays.asList(SpaceLevelEnum.values()).stream().map(SpaceLevelEnum -> new SpaceLevel(
                SpaceLevelEnum.getValue(),
                SpaceLevelEnum.getText(),
                SpaceLevelEnum.getMaxCount(),
                SpaceLevelEnum.getMaxSize()
        )).collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }
}
































